//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_eval_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type ResultScoreDbItem struct {
	ResultId     string `bson:"_id"`
	OrgId        string `bson:"orgId"`
	EvaluateId   string `bson:"evaluateId"`
	MemberUserId string `bson:"memberUserId"`
	TargetId     string `bson:"targetId"`
	TotalScore   uint32 `bson:"totalScore"`
}

type _ResultScoreDao struct {
	mc *mongo.Collection
}

func newResultScoreDao(db *mongo.Database) (*_ResultScoreDao, error) {
	mc := db.Collection(db_ns.DB_NS_ORG_EVAL + "result")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"orgId", 1}, {"evaluateId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ResultScoreDao{mc: mc}, nil
}

func (db *_ResultScoreDao) GenResultId(evaluateId, memberUserId, targetId string) string {
	return fmt.Sprintf("%s:%s:%s", evaluateId, memberUserId, targetId)
}

func (db *_ResultScoreDao) Insert(ctx context.Context, dbItem *ResultScoreDbItem) error {
	dbItem.ResultId = db.GenResultId(dbItem.EvaluateId, dbItem.MemberUserId, dbItem.TargetId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ResultScoreDao) UpdateScore(ctx context.Context, dbItem *ResultScoreDbItem) error {
	dbItem.ResultId = db.GenResultId(dbItem.EvaluateId, dbItem.MemberUserId, dbItem.TargetId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.ResultId, "orgId": dbItem.OrgId}, bson.M{
		"$set": bson.M{"totalScore": dbItem.TotalScore},
	})
	return err
}

func (db *_ResultScoreDao) List(ctx context.Context, orgId string, evaluateIdList []string) ([]*ResultScoreDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"orgId": orgId, "evaluateId": bson.M{"$in": evaluateIdList}})
	if err != nil {
		return nil, err
	}
	retList := []*ResultScoreDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ResultScoreDao) RemoveByEvaluate(ctx context.Context, orgId, evaluateId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId, "evaluateId": evaluateId})
	return err
}

func (db *_ResultScoreDao) RemoveByOrg(ctx context.Context, orgId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId})
	return err
}
